﻿using System.IO;
using System.Net;
using System.Text;

namespace BErPiDeviceV1
{
    public class WebServiceCommunicator
    {
        //// Usage: ControllerMessage = "ws test: " + wsCommunicator.TestWS("{\"message\":\"heello\"}");
        public string TestWS(string jsonString)
        {
            var responseString = string.Empty;

            try
            {
                var encoding = new ASCIIEncoding();
                string postData = jsonString;
                byte[] data = encoding.GetBytes(postData);

                var webRequest = (HttpWebRequest)WebRequest.Create("http://192.168.0.7:5000/testjson");
                webRequest.Timeout = 1000;
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = data.Length;
                webRequest.Method = "POST";
                var requestStream = webRequest.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();

                var response = webRequest.GetResponse();

                var responseStream = response.GetResponseStream();
                var streamReader = new StreamReader(responseStream);
                responseString = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                response.Close();
            }
            catch (System.Net.WebException wex)
            {
                throw wex;
            }

            return responseString;
        }
    }
}
